Ext.ns('App', 'App.control');


/*
 * The mapEditor window which provides a editing tool to draw the polygon and its center
 */


App.control.mapEditor = Ext.extend(Ext.Window, {
	onCancel: function(btn, e){
		this.hide()
	},
	onOK: function(btn, e){
		//saves the polygon and the center 
		//check if only one polygon is drawn	
		var mp = this.findByType('mappanel')[0];
		var results = mp.getValues();
		var geometry_val = '';
		var x, y;

		if (results.polygon){
			//save the geometry in the field
			var geojson_format = new OpenLayers.Format.GeoJSON();
			var geom = results.polygon.geometry.clone();
			//transform the geometry
			var geom = geom.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
			geometry_val =  geojson_format.write(geom)
			
		} 
		
		this.form.getForm().findField('geometry').setValue(geometry_val);
		
		
		if (results.center){
			//save the geometry in the field
			var geom = results.center.geometry.clone();
			//transform the geometry
			var geom = geom.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326")); 
			x = geom.x;
			y = geom.y;
			this.form.getForm().findField('x').setValue(x);
			this.form.getForm().findField('y').setValue(y);
		}
		 
		
		
		
		this.hide();	
		
		//update the mapControl
		
		var mCtrl = this.form.findByType('app_mapcontrol')[0];
		mCtrl.updateControl(geometry_val, [x,y]);
		
		
		
		
	},
	
    initComponent: function(){
        var config = {
			modal: true,
			maximizable: true,
			layout: 'fit', //in IE it wouldn't draw the panel correctly if this is not specifically defined.
            items: {
				xtype: 'mappanel',
				id: 'app-mappanel'
			},
			closeAction: 'hide'
			,buttons: [{
				text: 'OK',
				handler: this.onOK,
				scope: this
			}, {
				text: 'Cancel',
				handler: this.onCancel,
				scope: this
			}]
        }; // eo config object
        // apply config
		
		
        Ext.apply(this, Ext.apply(this.initialConfig, config));
        
        App.control.mapEditor.superclass.initComponent.apply(this, arguments);
    } // eo function initComponent
//    ,onRender: function(){
//        this.store.load();
//        
//        App.control.mapField.superclass.onRender.apply(this, arguments);
//    } // eo function onRender
});

Ext.reg('app_mapeditor', App.control.mapEditor);


